package com.af.security.auth.phone;

import com.af.security.auth.util.AfAuthenticationUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : zhenyun.su
 * @comment : 短信身份认证过滤器
 * @since : 2020-9-22
 */

public class PhoneVerificationCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    private boolean postOnly = true;

    public PhoneVerificationCodeAuthenticationFilter() {
        super(new AntPathRequestMatcher(AfAuthenticationUtils.login_url, AfAuthenticationUtils.login_method));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !AfAuthenticationUtils.login_method.equals(request.getMethod())) {
            throw new AuthenticationServiceException(
                    "Asu, Phone Authentication method not supported: " + request.getMethod());
        }

        PhoneUserDetails userDetails = AfAuthenticationUtils.obtainUserDetails(request);
        String phone = AfAuthenticationUtils.obtainPhone(request);
        String verificationCode = AfAuthenticationUtils.obtainVerificationCode(request);

        PhoneAuthenticationToken authRequest = new PhoneAuthenticationToken(userDetails, phone, verificationCode);
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }


    protected void setDetails(HttpServletRequest request, PhoneAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }
}